package com.example.presentshopping.ui.activity

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.PopupWindow
import android.widget.RelativeLayout
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.bean.AreaDataSsqEntity
import com.example.presentshopping.config.bean.CityModel
import com.example.presentshopping.config.bean.DistrictModel
import com.example.presentshopping.config.bean.ProvinceModel
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL.Req_editAddress
import com.example.presentshopping.ui.custom.LoacationView
import com.example.presentshopping.ui.custom.city.OnWheelChangedListener
import com.example.presentshopping.ui.custom.city.WheelView
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.unit.StringUtils
import com.lljjcoder.citypickerview.widget.CityPicker
import com.lljjcoder.citypickerview.widget.wheel.adapters.ArrayWheelAdapter
import io.reactivex.internal.util.NotificationLite.getValue
import kotlinx.android.synthetic.main.activity_order.*
import kotlinx.android.synthetic.main.activity_shippingaddress.*
import java.util.*


class ShippingaddressActivity : BaseMvpActivity() {

    var imm: InputMethodManager? = null
    private var queryInfoPresenter: PublicPresenter? = null
    var id = ""
    var auto = ""
     var mViewProvince: WheelView? = null
    var mViewCity: WheelView? = null
    var mViewDistrict: WheelView? = null

    private var mAreaPicker: View? = null
    var mPopTime: PopupWindow? = null
    private var areaDataEntity: AreaDataSsqEntity? = null

    override val layoutId: Int
        get() = R.layout.activity_shippingaddress

    override fun initView(savedInstanceState: Bundle?) {
        queryInfoPresenter = PublicPresenter(this, true, "提交中...")
        queryInfoPresenter?.attachView(this)

        title_bar_right_iv.setOnClickListener { finish() }
        mysaveLocat.setOnClickListener { serLocation() }

        ex_provinces.setOnClickListener {
//            imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
//            if (imm?.isActive!!) {
//                imm?.hideSoftInputFromWindow(
//                    it.getWindowToken(),
//                    InputMethodManager.HIDE_NOT_ALWAYS
//                );
//                selectAddress();//调用CityPicker选取区域
//            }

            LoacationView(this ,ex_provinces ,it , view_all)

        }

    }


    fun serLocation() {
        if (!TextUtils.isEmpty(ex_name.text)) {
            if (!TextUtils.isEmpty(ex_phone.text)) {
                if (!TextUtils.isEmpty(ex_provinces.text)) {

                    if (!TextUtils.isEmpty(ex_address.text)) {
                        queryInfoPresenter?.netWorkRequestPost(Req_editAddress,
                            HttpRequest.editAddress(id,
                                ex_name.text.toString(),
                                ex_phone.text.toString(),
                                ex_provinces.text.toString() + ex_address.text.toString(),
                                auto))

                    } else {
                        showToast("请输入详细地址 ")
                    }

                } else {
                    showToast("请选择所在地区 ")
                }

            } else {
                showToast("请输入收件人联系电话 ")

            }

        } else {
            showToast("请输入收件人姓名 ")
        }
        //
    }


    override fun onDestroy() {
        queryInfoPresenter?.detachView()
        super.onDestroy()
    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    override fun onSuccess(data: String?) {
        ToastUtil.showMsg("保存成功")
        finish()
    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    private fun selectAddress() {
        val cityPicker: CityPicker = CityPicker.Builder(this@ShippingaddressActivity)
            .textSize(14)
            .title("地址选择")
            .titleBackgroundColor("#FFFFFF")
            .confirTextColor("#696969")
            .cancelTextColor("#696969")
            .textColor(Color.parseColor("#000000"))
            .provinceCyclic(true)
            .cityCyclic(false)
            .districtCyclic(false)
            .visibleItemsCount(7)
            .itemPadding(10)
            .onlyShowProvinceAndCity(false)
            .build()
        cityPicker.show()
        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener { citySelected -> //省份
            val province = citySelected[0]
            //城市
            val city = citySelected[1]
            //区县（如果设定了两级联动，那么该项返回空）
            val district = citySelected[2]
            //邮编
            val code = citySelected[3]
            //为TextView赋值
            ex_provinces.setText(province.trim { it <= ' ' } + city.trim { it <= ' ' } + district.trim { it <= ' ' })
        }
    }

    /**
     * 半透明背景出现的动画
     */
    private fun propetyAnim(iv: View, vararg values: Float) {
        val animator = ObjectAnimator.ofFloat(iv, "alpha", *values)
        animator.duration = 500
        animator.repeatCount = 0
        animator.start()
        iv.visibility = View.VISIBLE
    }

    fun setLocatin(view: View) {
        val jsonData = StringUtils.readAssetsTxt(this, "json_ssq")
        // 滑轮界面
        mAreaPicker = View.inflate(this, R.layout.picker_area_layout33, null)
        mViewProvince = mAreaPicker?.findViewById<WheelView>(R.id.id_province) as WheelView
         mViewCity = mAreaPicker?.findViewById<View>(R.id.id_city) as WheelView
         mViewDistrict = mAreaPicker?.findViewById<View>(R.id.id_area) as WheelView
        //  if (isSecondLinage) mViewDistrict?.setVisibility(View.GONE) //
        mViewProvince?.addChangingListener(onChanged)
        mViewCity?.addChangingListener(onChanged)
        mViewDistrict?.addChangingListener(onChanged)




        mPopTime = PopupWindow(mAreaPicker,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
        mPopTime?.isOutsideTouchable = true
        mPopTime?.isFocusable = true
        mPopTime?.setBackgroundDrawable(ColorDrawable(0))
        mPopTime?.animationStyle = R.style.ActionSheetDialogStyle
        mPopTime?.setOnDismissListener {
            propetyAnim(view_all, 1f, 0.9f, 0.7f, 0.5f, 0.2f, 0f)
            mPopTime = null
        }
        mPopTime?.showAsDropDown(view)

        val tv_cancelStart = mAreaPicker!!.findViewById<View>(R.id.tv_cancel) as RelativeLayout
        val tv_confirmStart = mAreaPicker!!.findViewById<View>(R.id.tv_confirm) as RelativeLayout
        tv_cancelStart?.setOnClickListener {
            if (mPopTime != null) {
                mPopTime?.dismiss()
            }
        }
        tv_confirmStart?.setOnClickListener {

        }


    }

    val onChanged = OnWheelChangedListener { wheel, oldValue, newValue ->
    }

    /**
     * 解析数据
     */
    protected fun initProvinceDatas(jsonData :String) {

    }

}